package admin

import (
	"anban/logic"
	"anban/service"
	"anban/utils"
	"github.com/astaxie/beego"
	"html/template"
	"strconv"
)

type WeekCourseController struct {
	BaseController
}

func (c *WeekCourseController) Add() {
	userAdminId := c.GetSession("userAdminId")
	p := map[string]interface{}{}
	p["id"] = userAdminId
	p["relation"] = true
	userAdmin := service.GetUserAdminInfo(p)

	p = map[string]interface{}{}
	p["schoolId"] = userAdmin.UserAdminRole.School.Id
	_, c.Data["classList"] = service.GetClassList(p)

	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "admin/week_course/add.html"
}

func (c *WeekCourseController) DoAdd() {
	var res *utils.ResJsonStruct
	input := c.Input()

	err := logic.AddWeekCourse(input)
	if err != nil {
		res = utils.ResJson(err.Code(), err.Error(), "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	res = utils.ResJson(1, "发布成功", "")
	c.Data["json"] = res
	c.ServeJSON()
}

func (c *WeekCourseController) Edit() {
	id := c.Ctx.Input.Param(":id")

	p := map[string]interface{}{}
	p["id"] = id
	p["relation"] = true
	p["convert"] = true
	c.Data["record"] = service.GetWeekCourseInfo(p)

	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "admin/week_course/edit.html"
}

func (c *WeekCourseController) DoEdit() {
	var res *utils.ResJsonStruct
	input := c.Input()
	_, err := service.EditWeekCourse(input)
	if err != nil {
		res = utils.ResJson(0, "修改失败", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	res = utils.ResJson(1, "修改成功", "")
	c.Data["json"] = res
	c.ServeJSON()
}

func (c *WeekCourseController) ShowList() {
	curPage, _ := strconv.Atoi(c.GetString("p"))
	if curPage <= 0 {
		curPage = 1
	}
	perCount, _ := beego.AppConfig.Int("percount")
	symPageCount, _ := beego.AppConfig.Int("symmetricpagecount")

	userAdminId := c.GetSession("userAdminId")
	p := map[string]interface{}{}
	p["id"] = userAdminId
	p["relation"] = true
	userAdmin := service.GetUserAdminInfo(p)
	schoolId := userAdmin.UserAdminRole.School.Id

	p = map[string]interface{}{}
	p["schoolId"] = schoolId
	_, c.Data["classList"] = service.GetClassList(p)

	p = map[string]interface{}{}
	classId := c.GetString("class_id")
	if len(classId) > 0 {
		p["classId"] = classId
		c.Data["classId"] = utils.Atoi64(classId)
	} else {
		c.Data["classId"] = -1
	}
	p["schoolId"] = schoolId
	p["relation"] = true
	p["convert"] = true
	p["curPage"] = curPage
	p["perCount"] = perCount
	totalCount, recordList := service.GetWeekCourseList(p)

	paginator := utils.NewPaginator(int(totalCount), perCount, symPageCount, curPage)
	c.Data["paginator"] = paginator.GetPageHtml()
	c.Data["recordList"] = recordList

	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "admin/week_course/list.html"
}